package poo.file;

import java.util.Scanner;
import java.io.*;

public class AggiornamentoSelettivo {

	public static void main(String[] args) throws IOException {

		File f = new File("C:\\Users\\Paco\\Desktop\\prova213.txt");
		DataOutputStream dos = new DataOutputStream(new FileOutputStream(f));

		Scanner sc = new Scanner(System.in);
		System.out.println("intero da inserire");
		int x = sc.nextInt();

		inserisci(f, x);
		sc.close();
		dos.close();
	}

	private static void inserisci(File nome, int x) throws IOException {

		RandomAccessFile raf = new RandomAccessFile(nome, "r");
		DataOutputStream tmp = new DataOutputStream(new FileOutputStream("tmp"));

		long pos = 0;
		int y = 0;
		boolean flag = false;

		while (pos < raf.length() && !flag) {
			y = raf.readInt();
			if (y > x)
				flag = true;
			else {
				tmp.writeInt(y);
				pos = raf.getFilePointer();
			}
		}
		tmp.writeInt(x);
		if (flag) {
			for (;;) {
				tmp.writeInt(y);
				pos = raf.getFilePointer();
				if (pos == raf.length())
					break;
				y = raf.readInt();
			}
		}
		raf.close();
		tmp.close();
	}
}
